/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.aternity.vbd.ui;

import com.aternity.vbd.mgmt.AppManager;
import com.aternity.vbd.mgmt.Config;
import com.aternity.vbd.mgmt.ConfigManager;
import com.aternity.vbd.mgmt.ExportManager;
import com.aternity.vbd.mgmt.events.ConnectionDetailsChangeEvent;
import com.aternity.vbd.mgmt.events.CreateDbRequest;
import com.google.common.eventbus.EventBus;
import dnl.utils.swing.FileChooserUtils;
import dnl.utils.swing.WindowUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.swing.*;
import java.io.File;
import java.net.URL;

/**
 * @author Daniel Orr
 */
@Component
public class VbdManagementApp extends javax.swing.JFrame {

    @Autowired
    ExportManager exportManager;

    @Autowired
    AppManager appManager;

    @Autowired
    ConfigManager configManager;

    @Autowired
    EventBus eventBus;

    JdbcConfigDialog jdbcConfigDialog = new JdbcConfigDialog(this, true);

    @Autowired
    GeneralPanel generalPanel;

    @Autowired
    FeedbackPanel feedbackPanel;

    @Autowired
    LogsPanel logsPanel;

    /**
     * Creates new form VmdManagementApp
     */
    public VbdManagementApp() {
        initComponents();
        final URL url = getClass().getResource("aternity.gif");
        ImageIcon ii = new ImageIcon(url);
        setIconImage(ii.getImage());
    }

    @PostConstruct
    public void init() {
        jTabbedPane1.addTab("General", generalPanel);
        jTabbedPane1.addTab("Feedback", feedbackPanel);
        jTabbedPane1.addTab("Logs", logsPanel);
        eventBus.register(generalPanel);
        eventBus.register(feedbackPanel);
        eventBus.register(logsPanel);
    }

    /**
     * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this
     * code. The content of this method is always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTabbedPane1 = new javax.swing.JTabbedPane();
        menuBar = new javax.swing.JMenuBar();
        fileMenu = new javax.swing.JMenu();
        dbSettingsMI = new javax.swing.JMenuItem();
        exitMenuItem = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        dbCreateAllMI = new javax.swing.JMenuItem();
        dbDeleteAllMI = new javax.swing.JMenuItem();
        jMenuItem3 = new javax.swing.JMenuItem();
        jMenuItem4 = new javax.swing.JMenuItem();
        jMenuItem5 = new javax.swing.JMenuItem();
        feedbackMenu = new javax.swing.JMenu();
        newFeedbackMI = new javax.swing.JMenuItem();
        refreshMI = new javax.swing.JMenuItem();
        jMenu1 = new javax.swing.JMenu();
        exportDataMI = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Aternity Volume Based Detection Tool");
        getContentPane().add(jTabbedPane1, java.awt.BorderLayout.CENTER);

        fileMenu.setMnemonic('f');
        fileMenu.setText("Settings");

        dbSettingsMI.setMnemonic('o');
        dbSettingsMI.setText("DB Connection");
        dbSettingsMI.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                dbSettingsMIActionPerformed(evt);
            }
        });
        fileMenu.add(dbSettingsMI);

        exitMenuItem.setMnemonic('x');
        exitMenuItem.setText("Exit");
        exitMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        jMenu2.setText("DB");

        dbCreateAllMI.setText("Create All");
        dbCreateAllMI.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                dbCreateAllMIActionPerformed(evt);
            }
        });
        jMenu2.add(dbCreateAllMI);

        dbDeleteAllMI.setText("Delete All");
        jMenu2.add(dbDeleteAllMI);

        jMenuItem3.setText("Create Tables");
        jMenu2.add(jMenuItem3);

        jMenuItem4.setText("Create Procedures");
        jMenu2.add(jMenuItem4);

        jMenuItem5.setText("Register Job");
        jMenu2.add(jMenuItem5);

        menuBar.add(jMenu2);

        feedbackMenu.setMnemonic('e');
        feedbackMenu.setText("Feedback");
        feedbackMenu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                feedbackMenuActionPerformed(evt);
            }
        });

        newFeedbackMI.setMnemonic('d');
        newFeedbackMI.setText("New");
        newFeedbackMI.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newFeedbackMIActionPerformed(evt);
            }
        });
        feedbackMenu.add(newFeedbackMI);

        refreshMI.setText("Refresh");
        refreshMI.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                refreshMIActionPerformed(evt);
            }
        });
        feedbackMenu.add(refreshMI);

        menuBar.add(feedbackMenu);

        jMenu1.setText("Export");

        exportDataMI.setText("Export Data");
        exportDataMI.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exportDataMIActionPerformed(evt);
            }
        });
        jMenu1.add(exportDataMI);

        menuBar.add(jMenu1);

        setJMenuBar(menuBar);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitMenuItemActionPerformed
        System.exit(0);
    }//GEN-LAST:event_exitMenuItemActionPerformed

    private void dbSettingsMIActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_dbSettingsMIActionPerformed
        final Config config = configManager.getConfig();
        final Config copy = config.copy();
        jdbcConfigDialog.setData(copy);
        WindowUtils.centerWindowRelative(jdbcConfigDialog, this);
        jdbcConfigDialog.setVisible(true);

        if (!jdbcConfigDialog.wasCancelled()) {
            jdbcConfigDialog.readDataIntoConfig(copy);
            if (!copy.equals(config)) {
                configManager.setConfig(copy);
                configManager.saveConfiguration();
                eventBus.post(new ConnectionDetailsChangeEvent(copy.getJdbcUrl()));
            }
        }
    }//GEN-LAST:event_dbSettingsMIActionPerformed

    private void feedbackMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_feedbackMenuActionPerformed
        jTabbedPane1.setSelectedComponent(feedbackPanel);
    }//GEN-LAST:event_feedbackMenuActionPerformed

    private void newFeedbackMIActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newFeedbackMIActionPerformed
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                jTabbedPane1.setSelectedComponent(feedbackPanel);
                feedbackPanel.insertNewFeedback();
            }
        });
    }//GEN-LAST:event_newFeedbackMIActionPerformed

    private void refreshMIActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_refreshMIActionPerformed
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                jTabbedPane1.setSelectedComponent(feedbackPanel);
                feedbackPanel.refreshData();
            }
        });
    }//GEN-LAST:event_refreshMIActionPerformed

    private void exportDataMIActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exportDataMIActionPerformed
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                final File exportDir = FileChooserUtils.selectDirectory(VbdManagementApp.this);
                exportManager.exportTo(exportDir);
            }
        });

    }//GEN-LAST:event_exportDataMIActionPerformed

    private void dbCreateAllMIActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_dbCreateAllMIActionPerformed
        eventBus.post(new CreateDbRequest(false));
    }//GEN-LAST:event_dbCreateAllMIActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {

        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext-swingui.xml");
        final VbdManagementApp vbdManagementApp = (VbdManagementApp) applicationContext.getBean("vbdManagementApp");
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        setLnF();
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                WindowUtils.setWindowSize(vbdManagementApp, .6, .6);
                WindowUtils.centerWindow(vbdManagementApp);
                vbdManagementApp.setVisible(true);
            }
        });
    }

    private static void setLnF() {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(VbdManagementApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(VbdManagementApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(VbdManagementApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(VbdManagementApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem dbCreateAllMI;
    private javax.swing.JMenuItem dbDeleteAllMI;
    private javax.swing.JMenuItem dbSettingsMI;
    private javax.swing.JMenuItem exitMenuItem;
    private javax.swing.JMenuItem exportDataMI;
    private javax.swing.JMenu feedbackMenu;
    private javax.swing.JMenu fileMenu;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuItem jMenuItem3;
    private javax.swing.JMenuItem jMenuItem4;
    private javax.swing.JMenuItem jMenuItem5;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JMenuItem newFeedbackMI;
    private javax.swing.JMenuItem refreshMI;
    // End of variables declaration//GEN-END:variables

}
